package com.towker.frame.share.sys.user;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.context.ApplicationContext;

import com.towker.core.util.BeanUtils;
import com.towker.core.util.SpringContextUtil;
import com.towker.frame.model.sys.User;
import com.towker.frame.service.LoginService;
import com.towker.frame.service.sys.CacheHelper;
import com.towker.web.MyCookie;


public class UserShare
{

	public final static String LoginToken = "__token__";
	public final static String CurrentSystem = "__system__";
	public final static String Separator = "#";

	/**
	 * 判断用户是否已经选择了系统。	 */
	public static boolean isSystemChosen(HttpServletRequest request)
	{
		MyCookie myCookie = new MyCookie(request, null);
		// 判断cookie是否存在
		boolean isExist = myCookie.isExistByName(CurrentSystem);
		return isExist;
	}

	/**
	 * 判断用户是否已经登录。	 * @param request
	 * @return
	 * @throws Exception
	 */
	public static boolean isUserLogined(HttpServletRequest request)  
	{
		MyCookie myCookie = new MyCookie(request, null);
		HttpSession session = request.getSession();
		User sessionToken = (User)session.getAttribute(LoginToken);
	 	if (sessionToken != null) return true;
		// 判断cookieToken是否存在。
		boolean cookieTokenExists = myCookie.isExistByName(LoginToken);
		if (cookieTokenExists){
			String userToken=myCookie.getValueByName(LoginToken);
			//重新验证
			User user=getUserFromToken(userToken);
			if(user==null) return false;
			//重新加入缓存
			session.setAttribute(LoginToken, user);
			return true;
		}
		return false;
	}
	
	/**
	 * 取得当前登录用户的ID
	 * @param request
	 * @return
	 */
	public static Long getCurrentUserId(HttpServletRequest request)
	{
		User user = getCurrentUser(request);
		if (user == null) return 0L;
		return user.getId();
	}

	/**取得当前用户所选择的系统ID*/
	public static long getCurrentSystemId(HttpServletRequest request)
	{
		MyCookie myCookie = new MyCookie(request, null);
		String value = myCookie.getValueByName(CurrentSystem);
		if (null == value)return 0;
		return Long.parseLong(value);
	}
	/**取得当前登录用户帐号*/
	public static String getCurrentUserAccount(HttpServletRequest request)
	{
		User user = getCurrentUser(request);
		if (null!= user)return user.getAccount();
		return"";
	}
	/**取得当前登录用户名称*/
	public static String getCurrentUserName(HttpServletRequest request)
	{
		User user = getCurrentUser(request);
		if (null!=user)return user.getName();
		return"";
	}
	
	/**
	 * 取得当前登录用户代码
	 * @param request
	 * @return
	 */
	public static String getCurrentUserCode(HttpServletRequest request) {
		User user = getCurrentUser(request);
		if (null!=user)return user.getUserCode();
		return"";
	}
	
	/**
	 * 取得当前登录用户的性质(1:公司员工　2:经销商或客户)
	 * @param request
	 * @return
	 */
	public static Integer getUserNature(HttpServletRequest request) {
		User user = getCurrentUser(request);
		if (null!=user)
			return user.getUserNature() == null ? 0 : user.getUserNature();
		return 0;
	}
	
	/**
	 * 取得当前登录用户客户代码
	 * @param request
	 * @return
	 */
	public static String getCurrentCustomCode(HttpServletRequest request) {
		User user = getCurrentUser(request);
		if (null!=user)return user.getCustomCode();
		return"";
	}
	/**
	 * 取得当前登录用户公司ID
	 * @param request
	 * @return
	 */
	public static Integer getCurrentUserCoId(HttpServletRequest request) {
		User user = getCurrentUser(request);
		if (null!=user)return user.getCoId();
		return 0;
	}
	
	/**
	 * 取得当前登录用户公司代码,当用户数据权限为可查看所有时返回 null
	 * 
	 * @param request
	 * @return
	 */
	public static String getCurrentUserCoCode(HttpServletRequest request) {
		User user = getCurrentUser(request);
		if (null != user && "S".equals(user.getDataAuthType()))
			return user.getCoCode();
		return null;
	}
	/**
	 * 取得当前登录用户公司名称
	 * @param request
	 * @return
	 */
	public static String getCurrentUserCoName(HttpServletRequest request) {
		User user = getCurrentUser(request);
		if (null!=user)return user.getCoName();
		return "";
	}
	
	/**
	 * 取得当前登录用户部门代码
	 * @param request
	 * @return
	 */
	public static String getCurrentUserDepCode(HttpServletRequest request) {
		User user = getCurrentUser(request);
		if (null!=user)return user.getDeptCode();
		return "";
	}
	
	/**
	 * 取得当前登录用户对象
	 * @param request
	 * @return
	 */
	public static User getCurrentUser(HttpServletRequest request)  
	{
		MyCookie myCookie = new MyCookie(request, null);
		HttpSession session = request.getSession();
		User user=(User)session.getAttribute(LoginToken);
		if(user!=null) return user;
		// 从cookie中读取。
		String cookieToken = myCookie.getValueByName(LoginToken);
		if(cookieToken==null) return null;
		user=getUserFromToken(cookieToken);
		//将用户添加到session
		if(user!=null)
			session.setAttribute(LoginToken, user);
		return user;
	}
	
	/**设置用户选择的当前系统ID*/
	public static void setCurrentSystemId(HttpServletRequest req, HttpServletResponse res, String systemid)
	{
		MyCookie cookie = new MyCookie(req, res);
		cookie.addCookie(CurrentSystem, systemid);
	}
	/**设置用户登录*/
	public static void setUserLogined(HttpServletRequest req, HttpServletResponse res, User user) throws UnsupportedEncodingException
	{

		
		HttpSession session = req.getSession();
		session.setAttribute(LoginToken, user);
		session.setAttribute("longinedUserType", user.getUsertype());
		session.setAttribute("loginedUserName", user.getName());
		session.setAttribute("loginedUserCode", user.getUserCode());
		session.setAttribute("userId", user.getId());
		//id#account#name#password
		String loginTokenValueCookie=user.getId() + Separator + user.getAccount() +Separator + user.getPassword();
		MyCookie cookie = new MyCookie(req, res);
		cookie.addCookie(LoginToken, loginTokenValueCookie);
	}
	
	/**获得缓存数据的键名*/
	public static String getKey(HttpServletRequest request){
		String currentUserId=getCurrentUserId(request) +"";
		String currentSystemId=getCurrentSystemId(request) +"";
		String key=currentUserId+":"+currentSystemId;
		return key;
	}
	/**用户登出系统*/
	public static void logout(HttpServletRequest req, HttpServletResponse res)
	{
		UserShare.clearCache(req);		HttpSession session = req.getSession();
		session.removeAttribute(LoginToken);
		session.removeAttribute("hyjc");
		session.removeAttribute(CurrentSystem);
		// cookie的。		MyCookie cookie = new MyCookie(req, res);
		cookie.delCookie(LoginToken);
		cookie.delCookie(CurrentSystem);

	}
	/**清除当前用户的一些缓存。 比如资源列表，资源json树，导航栏json树等*/
	public static void clearCache(HttpServletRequest request)
	{
		String key=getKey(request);
		CacheHelper.clearAllMaps(key);
	}

	/**
	 * 防止用户在客服端利用欺骗手段进入。	 * @throws Exception
	 */
	private static User getUserFromToken(String userToken)  
	{
		try
		{
			//id#account#name#password
			
			LoginService loginManager =(LoginService) BeanUtils.getBean(LoginService.class);
			String[] aryToken=userToken.split(Separator);
			if(aryToken.length!=3)   return null;
			//帐号
			String account=aryToken[1];
			//密码
			String password=aryToken[2];
			//系统登录验证。
			User user = loginManager.login(account, password);
			return user;
		}
		catch(Exception ex)
		{
			return null;
		}
		
	}
}
